package com.xshang.mybatis;

import com.xshang.tenant.TenantDataSourceContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.task.TaskDecorator;
import org.springframework.lang.NonNull;

/**
 * 租户数据源上下文Decorator，用于异步线程/跨线程间传递租户id信息
 */
@Slf4j
public class TenantDataSourceContextDecorator implements TaskDecorator {
    @Override
    public Runnable decorate(@NonNull Runnable runnable) {
        // 获取主线程的dataSourceName
        String dataSourceName = TenantDataSourceContext.get();
        return () -> {
            try {
                // 将主线程的dataSourceName，设置到子线程中
                TenantDataSourceContext.set(dataSourceName);
                // 执行子线程
                runnable.run();
            } finally {
                // 子线程结束，清空dataSourceName
                TenantDataSourceContext.clear();
                log.info("TenantDataSourceContextDecorator clear dataSourceName.");
            }
        };
    }
}

